<template>
  <el-dialog v-model="visible" :title="title" width="650px" :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="product-form"
    >
      <!-- 基础信息 -->
      <div class="section-title">
        <span>基础信息</span>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="请输入商品名称" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品标题" prop="productTitle">
              <el-input
                v-model="formData.productTitle"
                maxlength="150"
                show-word-limit
                placeholder="请输入商品展示标题"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品规格" prop="productSpec">
              <el-input v-model="formData.productSpec" placeholder="例如：一盒10包" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="usageType">
              <el-select v-model="formData.usageType" placeholder="请选择" :options="goodsType" />
            </el-form-item>
          </el-col>
          <!-- isGift 是否赠品 -->
          <el-col :span="12">
            <el-form-item label="是否赠品" prop="isGift">
              <el-radio-group v-model="formData.isGift">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图" prop="productImage">
          <ImageUpload
            v-model="formData.productImage"
            action="/common/upload"
            class="upload-box"
            :limit="3"
            :file-type="['png', 'jpg', 'jpeg']"
            :is-show-tip="true"
          />
        </el-form-item>
      </div>
      <div class="section-title">
        <span>库存与价格</span>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数量" prop="productUnitNum">
              <el-input-number
                v-model="formData.productUnitNum"
                controls-position="right"
                :min="1"
                :max="9999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input-number
                v-model="formData.costPrice"
                controls-position="right"
                :precision="2"
                :step="0.01"
                :min="0"
                style="width: 100%"
              >
                <template #prefix>￥</template>
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="销售价" prop="salePrice">
              <el-input-number
                v-model="formData.salePrice"
                controls-position="right"
                :precision="2"
                :step="0.01"
                :min="0"
                style="width: 100%"
              >
                <template #prefix>￥</template>
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="库存量" prop="stock">
              <el-input-number
                controls-position="right"
                v-model="formData.stock"
                :min="0"
                :max="99999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            maxlength="200"
            show-word-limit
            placeholder="请输入商品备注信息（选填）"
          />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          {{ formData.productId ? '编辑' : '新增' }}
        </el-button>
        <el-button @click="hide">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { addProduct, updateProduct } from '../../api/goods';

const formRef = ref();
const visible = ref(false);
const submitLoading = ref(false);
const emits = defineEmits(['ok']);

const defaultData = {
  productId: '',
  productName: '',
  productSpec: '',
  productTitle: '',
  productImage: [],
  productUnitNum: 1,
  usageType: '', // 商品分类
  costPrice: null,
  salePrice: null,
  stock: null,
  remark: '',
  isGift: 0, // 是否赠品
  type: 1, // 自己创建的商品是 自营
  externalType: 0 // 这个窗口创建的都是 普通商品
};

const formData = reactive<any>({ ...defaultData });

const title = ref('');
// 改为props
defineProps({
  goodsType: {
    type: Array,
    default: () => []
  }
});

const checkSalePrice = (_rule: any, value: any, callback: any) => {
  if (value < formData.costPrice) {
    callback(new Error('销售价不能低于成本价'));
  } else {
    callback();
  }
};

const rules = {
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  productSpec: [{ required: true, message: '请输入商品规格', trigger: 'blur' }],
  usageType: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  productImage: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  isGift: [{ required: true, message: '请选择是否赠品', trigger: 'change' }],
  productTitle: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
  productUnitNum: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  costPrice: [{ required: true, message: '请输入成本价', trigger: 'blur' }],
  salePrice: [
    { required: true, message: '请输入销售价', trigger: 'blur' },
    {
      validator: checkSalePrice,
      trigger: 'blur'
    }
  ],
  stock: [{ required: true, message: '请输入库存量', trigger: 'blur' }]
};

const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    submitLoading.value = true;
    if (formData.productId) {
      updateProduct(formData).then((res: any) => {
        submitLoading.value = false;
        if (res.code === 200) {
          ElMessage.success('商品编辑成功！');
          hide();
          emits('ok');
        }
      });
    } else {
      addProduct(formData).then((res: any) => {
        submitLoading.value = false;
        if (res.code === 200) {
          ElMessage.success('商品添加成功！');
          hide();
          emits('ok');
        }
      });
    }
  });
};

const hide = () => {
  visible.value = false;
  formRef.value.resetFields();
};
const show = (data: string) => {
  if (data) {
    title.value = '商品编辑';
    Object.assign(formData, data);
  } else {
    title.value = '新增商品';
    Object.assign(formData, defaultData);
  }
  visible.value = true;
};

defineExpose({
  show,
  hide
});
</script>

<style scoped lang="scss">
.product-form {
  .section-title {
    border: 1px solid #ebebeb;
    padding-right: 20px;
    box-sizing: border-box;
    border-radius: 4px;

    &:first-child {
      margin-bottom: 10px;
    }

    & > span {
      display: inline-block;
      padding: 5px 10px;
      background: #ebebeb;
      font-size: 13px;
      margin-bottom: 10px;
      border-radius: 0 4px 4px 0;
    }
  }
}

.dialog-footer {
  text-align: center;
}
</style>
